<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/5/28
 * Time: 09:09
 */

namespace Home\Controller;


use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Aliyun\Core\Config;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Core\Profile\DefaultProfile;
use Common\Utils\Constants;
use Home\Logic\UserLogic;
use Think\Controller;

class LoginController extends Controller
{

    private static $_validate = array(
        array('game_name', 'require', '请填写游戏昵称！', 1, 'regex', 3),
        array('wechat_number', 'require', '请填写微信号！', 1, 'regex', 3),
//        array('qq_number', 'require', '请填写QQ号！', 1, 'regex', 3),
        array('region_name', 'require', '请选择地区！', 1, 'regex', 3),
        array('systems_name', 'require', '请选择手机系统！', 1, 'regex', 3),
        array('region', 'require', '请选择游戏战区！', 1, 'regex', 3),
        array('level', 'require', '请选择段位信息！', 1, 'regex', 3),
        array('phone', 'require', '请填写手机号！', 1, 'regex', 3),
        array('code', 'require', '请填写验证码！', 1, 'regex', 3),
        array('password', 'require', '请填写密码！', 1, 'regex', 3),
        array('nickname', 'require', '请填写微信昵称！', 1, 'regex', 3),
    );

    protected function getSystemName(){
        $system_name = M('Config')->where(array('name'=>Constants::CONFIG_SYSTEM_NAME))->getField('value');
        return $system_name;
    }

    public function loginUI(){
        cookie('user','');
        $this->assign('system_name',$this->getSystemName());
        $this->display('login');
    }

    public function registerUI(){
        cookie('user','');
        $parent_id = I('parent_id',0);
        $this->assign('parent_id',$parent_id);
        $config = D('Config')->where(array('name'=>Constants::CONFIG_REGISTER_REWARD_INTEGRAL))->find();
        $money = $config['value'];
        if(!is_numeric($money) || $money < 0) {//奖励钻石
            $money = 0;
        }
        $this->assign('integral',$money);
        $this->assign('system_name',$this->getSystemName());
        $this->display('register');
    }

    public function doLogin(){
        $phone = I('phone');
        $password = I('password');
        if(empty($phone)){
            $this->ajax(false,'请输入手机号！');
        }
        if(empty($password)){
            $this->ajax(false,'请输入密码！');
        }
        $user = M('User')->where(array('phone'=>$phone))->find();
        if(!$user){
            $this->ajax(false,'用户名或密码错误！');
        }
        $password = md5($password.''.$user['register_time']);
        if($password != $user['password']){
            $this->ajax(false,'用户名或密码错误！');
        }
        cookie('user',$user, 3600 * 24);
        $url = U('Home/Index/index');
        $this->ajax(true,'登录成功',1,['url'=>$url]);
    }

    /**
     * 设置用户信息
     */
    public function ajaxSetUserInfo(){
        $model = D('User');
        $phone = I('phone');
        $code = I('code');
        $parent_id = I('parent_id',0);
        $password = I('password');
        $re_password = I('re_password');
        $data = $model->validate(self::$_validate)->create(I('post.'), 1);
        if (!$data) {
            $this->ajax(false,$model->getError());
        }
//        if(!isMobile($phone)){
//            $this->ajax(false,'请填写正确的手机号！');
//        }
        $sessionCode = session('code');
        $sessionPhone = session('number');
        if($code != $sessionCode){
            $this->ajax(false,'验证码不正确！');
        }
        if($phone != $sessionPhone){
            $this->ajax(false,'该手机号未验证！');
        }
        if(empty($password)){
            $this->ajax(false,'请填写密码！');
        }
        if($password != $re_password){
            $this->ajax(false,'密码不一致！');
        }
        $count = M('User')->where(array('phone'=>$phone))->count();
        if($count > 0){
            $this->ajax(false,'手机号已经被注册过！');
        }
        $logic = new UserLogic();
        if(!empty($parent_id)){
            $data['recommend_id'] = $parent_id;
        }
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]";
        $data['head_url'] = $url.'/Public/images/default_image.jpeg';
        $result = $logic->addUserInfo($data);
        $success = false;
        if($result == 0){
            $message = '注册失败！';
        }else{
            session('number','');
            session('code','');
            $success = true;
            $message = '注册成功！';
        }
        $data = array('is_first',1);
        $this->ajax($success,$message,-1,$data);
    }

    /**
     * ajax获取短信验证码
     */
    public function getCode(){
        $phone = I('phone');
        if(empty($phone) || !is_numeric($phone)){
            $this->ajax(false,'手机号输入有误，请重新输入！');
        }
        $create_time = session('create_time');
        $time = C('SMS_TIME');
        if (!empty($create_time) && time() - $create_time < $time) {
            $this->ajax(false,'不能重复获取！');
        }
        require_once  './Api/dysms/vendor/autoload.php';    //此处为你放置API的路径
        Config::load();             //加载区域结点配置
        if(empty($user['phone'])){
            $templateCode = Constants::SMS_TEMPLATE_REGISTER;
        }else{
            $templateCode = Constants::SMS_TEMPLATE_MODIFY;
        }
        $accessKeyId = C('APP_KEY');//参考本文档步骤2
        $accessKeySecret =  C('APP_SECRET');//参考本文档步骤2
        //短信API产品名（短信产品名固定，无需修改）
        $product = "Dysmsapi";
        //短信API产品域名（接口地址固定，无需修改）
        $domain = "dysmsapi.aliyuncs.com";
        //暂时不支持多Region（目前仅支持cn-hangzhou请勿修改）
        $region = "cn-hangzhou";
        //初始化访问的acsCleint
        $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
        DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
        $acsClient= new DefaultAcsClient($profile);
        $request = new SendSmsRequest;
        //必填-短信接收号码。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
        $request->setPhoneNumbers($phone);
        //必填-短信签名
        $request->setSignName(C('SIGN_NAME'));
        //必填-短信模板Code
        $request->setTemplateCode($templateCode);
        //选填-假如模板中存在变量需要替换则为必填(JSON格式),友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        $code = rand(100000, 999999);
        $request->setTemplateParam("{\"code\":\"".$code."\"}");
        //选填-发送短信流水号
        $request->setOutId(build_order_no());
        //发起访问请求
        $acsResponse = $acsClient->getAcsResponse($request);
        $result = json_decode(json_encode($acsResponse), true);
        if($result['Code'] == 'OK'){
            session('number',$phone);
            session('code',$code);
            $this->ajax(true,'已经发送成功！');
        }else{
            $this->ajax(false,'发送失败！',-1,$result);
        }
    }

    /**
     * @param $success
     * @param $message
     * @param int $code
     * @param array $data
     */
    protected function ajax($success,$message,$code=-1,$data=array()){
        $this->ajaxReturn(array(Constants::SUCCESS=>$success,Constants::MESSAGE=>$message,'data'=>$data,'code'=>$code));
    }
}